﻿using System.Web;
using System.Web.Routing;
using Isis.Controllers;
using Isis.Interfaces;
using Isis.Parsers.Impl;
using Isis.Parsers.Interfaces;

namespace Isis.Handlers
{
    public class ControlPanelHandler : IHttpHandler
    {
        private readonly IControllerRepository _controllerRepository;
        private readonly IRouteDataParser _routeDataParser;
        private readonly RequestContext _requestContext;
        private const string BASE_ISIS_CONTROLPANEL_URL = "/isis";

        public ControlPanelHandler(RequestContext requestContext) : this(new ControllerRepository(), new RouteDataParser(), requestContext)
        {
        }

        public ControlPanelHandler(IControllerRepository controllerRepository, IRouteDataParser routeDataParser, RequestContext requestContext)
        {
            _controllerRepository = controllerRepository;
            _routeDataParser = routeDataParser;
            _requestContext = requestContext;
        }

        public ControlPanelHandler()
        {
        }

        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            string controllerName = _routeDataParser.GetController(_requestContext);
            string actionName = _routeDataParser.GetAction(_requestContext);
            string parameterName = _routeDataParser.GetParameter(_requestContext);

            IControlPanelController controller = _controllerRepository.GetControllerByName(controllerName) ??
                                                 new HomePageController(BASE_ISIS_CONTROLPANEL_URL);


            controller.Action = actionName;
            controller.Parameter = parameterName;
            controller.Render(context.Response.Output);
            return;
        }
    }
}